import 'package:blog/screens/components/articles_container.dart';
import 'package:blog/src/generated/models/article.pb.dart';
import 'package:blog/tools/build.dart';
import 'package:flutter/material.dart';

import '../src/generated/models/category.pb.dart';
import '../src/generated/response/home_data.pb.dart';
import '/constants.dart';
import '/responsive.dart';
import '/api/api.dart';
import '/locator.dart';

import 'components/article_item.dart';
import 'components/categories.dart';
import 'components/recent_articles.dart';
import 'components/search.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({
    Key? key,
  }) : super(key: key);

  @override
  State<HomeScreen> createState() {
    return _HomeState();
  }
}

class _HomeState extends State<HomeScreen> {
  List<ArticleItem> articles = [];
  List<ArticleItem> recentArticles = [];
  List<CategoryItem> categories = [];

  Future<HomeData?> getHomeData() async {
    var homeData = await locator<Api>().getHomePage();
    if (homeData != null) {
      articles = homeData.articles;
      categories = homeData.categories;
      recentArticles = homeData.recentArticles;
    }
    return homeData;
  }

  List<Widget> getMobileSideBar() {
    return [
      SizedBox(width: kDefaultPadding),
      Expanded(
        child: Column(
          children: [
            Search(),
            SizedBox(height: kDefaultPadding),
            Categories(categoryList: categories),
            SizedBox(height: kDefaultPadding),
            RecentArticles(articles: recentArticles),
          ],
        ),
      )
    ];
  }

  Widget getHomePageContent() {
    return Container(
      constraints: BoxConstraints(maxHeight: 2000),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              flex: 2,
              child: ArticlesContainer(articles: articles, filter: {})),
          if (!Responsive.isMobile(context)) ...getMobileSideBar(),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getHomeData(),
        builder: BuilderTool.futureBuild((data) => getHomePageContent()));
  }
}
